﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;

namespace BreadWebRole
{
    public class DailyBreadTableStorageContext : TableServiceContext
    {
        private static CloudStorageAccount account; 
        public static string CommentTableName = "Comments";
        public static string FavTableName = "Favorites";
        public static string LogTableName = "Logs";
 
        static DailyBreadTableStorageContext() 
        {
            // This code sets up a handler to update CloudStorageAccount instances when their corresponding
            // configuration settings change in the service configuration file.
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(ConfigurationManager.AppSettings[configName].ToString());
            });
            account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); 
            CloudTableClient tableClient = new CloudTableClient(account.TableEndpoint.AbsoluteUri, account.Credentials);
            tableClient.CreateTableIfNotExist(CommentTableName);
            tableClient.CreateTableIfNotExist(FavTableName);
            tableClient.CreateTableIfNotExist(LogTableName);
        } 

        public DailyBreadTableStorageContext()
            : base(account.TableEndpoint.AbsoluteUri, account.Credentials)
        {
        }

        #region comment table operations
        public IQueryable<DailyBreadComments> Comments
        {
            get
            {
                return this.CreateQuery<DailyBreadComments>(CommentTableName);
            }
        }

        #endregion

        #region Favorites table operations
        public IQueryable<DailyBreadFavorites> Favorites
        {
            get
            {
                return this.CreateQuery<DailyBreadFavorites>(FavTableName);
            }
        }

        #endregion

        public IQueryable<DailyBreadLogs> Logs
        {
            get
            {
                return this.CreateQuery<DailyBreadLogs>(LogTableName);
            }
        }

    }
}